﻿using System;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TimerTask.Bll;
using TimerTask.Common.Utils;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace TimerTask.Web.Controllers
{
    public class AccountController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            //判断Cookie[token]：userName|md5Hash
            string token = HttpContext.Request.Cookies["token"];
            Regex regex = new Regex(@"^.+?[|].{32}$");
            if (token != null)
            {
                token = Base64Util.DeBase64(token);

                if (regex.Match(token).Success)
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public IActionResult Login(string userName, string pwd)
        {
            AccountBll bll = new AccountBll();
            var result = bll.Login(userName, pwd);
            if (result.Code == 1)
            {
                HttpContext.Response.Cookies.Append("token", Base64Util.EnBase64(userName.Trim() + "|" + result.Data), new CookieOptions
                {
                    Expires = DateTime.Now.AddMinutes(30)
                });
                result.Data = Url.Action("Index", "Home");
            }
            return Json(result);
        }

        /// <summary>
        /// 退出
        /// author:肖阳
        /// date:2016-10-22 09:13:35
        /// </summary>
        /// <returns></returns>
        public IActionResult Logout()
        {
            HttpContext.Response.Cookies.Delete("token");
            return RedirectToAction("Index");
        }
    }
}
